package com.canbot.u05.activity.dance

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration
import com.canbot.u05.activity.logd
import com.canbot.u05.activity.loge
import com.canbot.u05.activity.showToast
import com.canbot.u05.adapter.dance.DanceMusicAdapter
import com.canbot.u05.bean.Audio
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.bean.dance.DanceMusicItemBean
import com.canbot.u05.network.DanceUtil
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.DisplayUtils
import com.canbot.u05.utils.Logger
import com.canbot.u05.utils.PathConst
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_choose_music.*

class ChooseMusicActivity : BaseActivityNoTitle() {
        private val mbrowList: MutableList<DanceMusicItemBean> = mutableListOf()
        private lateinit var context: Context
        private val constant = 8
        private var homePage: Int = 0
        private var index: Int = 0
        private var selectedMusic: String = ""
        private var dialogLoading: Dialog? = null
        private val tipNoSound = listOf("mygq_wdgj_u05_001.mp3","mygq_wdgj_u05_002.mp3")
        private val tipSound = listOf("xzgq_wdgj_u05_001.mp3","xzgq_wdgj_u05_002.mp3")
        override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_choose_music)
                context = this
                initView()
                initData()
                dance_viewpager_industry.adapter = pagerAdapter
                dance_viewpager_industry.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                        override fun onPageScrolled(i: Int, v: Float, i1: Int) {}

                        override fun onPageSelected(i: Int) {
                                homePage = i
                                isPress(i)

                        }

                        override fun onPageScrollStateChanged(i: Int) {

                        }
                })
                dance_left.isSelected = true
                dance_right.isSelected = true
        }

        fun isPress(homePage: Int) {
                when (homePage) {
                        0 -> {
                                dance_left.isSelected = true
                                dance_right.isSelected = false
                        }
                        (mbrowList.size + (constant-1)) / constant - 1 -> {
                                dance_right.isSelected = true
                                dance_left.isSelected = false
                        }
                        else -> {
                                dance_left.isSelected = false
                                dance_right.isSelected = false
                        }
                }
        }

        private fun initData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this@ChooseMusicActivity, resources.getString(R.string.request))
                dialogLoading?.show()
                DanceUtil.getAudioList("/dance_music", object : DanceUtil.DanceCallBack<JsonResponse> {
                        override fun onSuccess(result: JsonResponse) {
                                dialogLoading?.dismiss()
                                if (result.rc == 0) {
                                        val audios = JSON.parseArray(result.result.toString(), Audio::class.java)
                                        logd("音频数据：" + audios)
                                        audios.forEach {
                                                val dancePicItemBean = DanceMusicItemBean(it, false) { index, audio ->
                                                        logd("选择音乐：" + audio)
                                                        selectedMusic = JSON.toJSONString(audio)
                                                        mbrowList.forEach {
                                                                it.isChecked = false
                                                        }
                                                        val dancePicItemBean = mbrowList.get(homePage * constant + index)
                                                        dancePicItemBean.isChecked = true
                                                        mbrowList[homePage * constant + index] = dancePicItemBean
                                                        pagerAdapter.notifyDataSetChanged()
                                                }
                                                mbrowList.add(dancePicItemBean)
                                        }

                                        if (audios.isEmpty()) {
                                                empty.visibility = View.VISIBLE
                                                dance_left.visibility = View.GONE
                                                dance_right.visibility = View.GONE
                                                dance_choose_music_title.visibility = View.GONE
                                                btn_next_step.visibility = View.GONE
                                                val random = (0..1).random()
                                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.PAD_DANCE_TIP_PATH + tipNoSound[random])
                                        } else {
                                                empty.visibility = View.GONE
                                                val pageSize = (mbrowList.size + (constant-1)) / constant
                                                if (pageSize > 1) {
                                                        dance_left.isSelected = true
                                                        dance_right.isSelected = false
                                                } else {
                                                        dance_left.isSelected = true
                                                        dance_right.isSelected = true
                                                }
                                                val random = (0..1).random()
                                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.PAD_DANCE_TIP_PATH + tipSound[random])
                                                pagerAdapter.notifyDataSetChanged()
                                        }
                                } else {
                                        loge(result.msg + "")
                                }
                        }

                        override fun onFailure() {
                                showToast("访问服务器异常，请检查网络")
                                dialogLoading?.dismiss()
                        }

                })
        }

        private fun initView() {
                btn_back.setOnClickListener {
                        finish()
                        overridePendingTransition(R.anim.face_zoom_enter,
                                R.anim.face_zoom_exit)
                }
                //下一步
                btn_next_step.setOnClickListener {
                        if (TextUtils.isEmpty(selectedMusic)) {
                                showToast("请选择歌曲")
                                return@setOnClickListener
                        }
                        val intent = Intent(context,ChooseDanceActionActivity::class.java)
                        intent.putExtra("music",selectedMusic)
                        startActivity(intent)
                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit)
                        //进入编辑舞蹈的界面
                }
                dance_left.setOnClickListener {
                        Logger.e(DanceManagerActivity.TAG, "左边按钮")
                        if (dance_viewpager_industry.currentItem == 0) {
                                Logger.e(DanceManagerActivity.TAG, "mViewPager.getCurrentItem() = " + dance_viewpager_industry.currentItem)
                                return@setOnClickListener
                        } else {
                                dance_viewpager_industry.setCurrentItem(dance_viewpager_industry.currentItem - 1, true)
                        }
                }
                dance_right.setOnClickListener {
                        Logger.e(DanceManagerActivity.TAG, "右边按钮")
                        if (dance_viewpager_industry.currentItem == pagerAdapter.count - 1) {
                                Logger.e(DanceManagerActivity.TAG, "mViewPager.getCurrentItem() = " + dance_viewpager_industry.currentItem)
                                return@setOnClickListener
                        } else {
                                dance_viewpager_industry.setCurrentItem(dance_viewpager_industry.currentItem + 1, true)
                        }
                }
        }

        override fun onPause() {
                super.onPause()
                dialogLoading?.dismiss()
        }
        private val pagerAdapter = object : PagerAdapter() {

                override fun isViewFromObject(arg0: View, arg1: Any): Boolean {

                        return arg0 === arg1
                }

                override fun getCount(): Int {

                        return (mbrowList.size + (constant-1)) / constant
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                        container.removeView(`object` as View)
                }

                override fun instantiateItem(container: ViewGroup, position: Int): Any {
                        val inflater = LayoutInflater.from(container.context)
                        val view = inflater.inflate(R.layout.layout_dance_recyclerview, container, false)

                        val mbrowList1 = mbrowList.subList(position * constant, if (position * constant + constant > mbrowList.size) mbrowList.size else position * constant + constant)
                        val recyclerView = view.findViewById<RecyclerView>(R.id.gv_content_action)
                        recyclerView.layoutManager = GridLayoutManager(context, 4)  //网格布局，每行为4
                        recyclerView.addItemDecoration(GridSpacingItemDecoration(4, DisplayUtils.dip2px(context, 24f), false))
                        val actionAdapter = DanceMusicAdapter(context, mbrowList1)
                        recyclerView.adapter = actionAdapter
                        actionAdapter.setIndex(index)
                        container.addView(view)

                        return view
                }

                override fun getItemPosition(`object`: Any): Int {
                        return PagerAdapter.POSITION_NONE
                }
        }
}
